import {
  Controller,
  Post,
  Get,
  Delete,
  Param,
  UseInterceptors,
  UploadedFile,
  Body,
  ParseIntPipe,
  Res,
  BadRequestException,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ImagesService } from './images.service';
import { UploadImageDto } from './upload-image.dto';
import { multerConfig } from '../../config/multer.config';
import { Response } from 'express';
import { join } from 'path';
import { existsSync } from 'fs';

@Controller('images')
export class ImagesController {
  constructor(private readonly imagesService: ImagesService) {}

  @Post('upload')
  @UseInterceptors(FileInterceptor('image', multerConfig))
  async uploadImage(
    @UploadedFile() file: Express.Multer.File, // 相当于 var file = req.file
    @Body() uploadImageDto: UploadImageDto,
  ) {
    if (!file) {
      throw new BadRequestException('请选择要上传的图片');
    }
    const image = await this.imagesService.saveImage(
      file,
      uploadImageDto.description,
    );
    return {
      message: '图片上传成功',
      data: {
        id: image.id,
        filename: image.filename,
        originalName: image.originalName,
        url: image.url,
        size: image.size,
        mimetype: image.mimetype,
        description: image.description,
        uploadedAt: image.createdAt,
      },
    };
  }

  @Get("getImages")
  async getAllImages() {
    const images = await this.imagesService.findAll();
    return {
      message: '获取图片列表成功',
      data: images,
    };
  }

  @Get(':id')
  async getImage(@Param('id', ParseIntPipe) id: number) {
    const image = await this.imagesService.findOne(id);
    return {
      message: '获取图片信息成功',
      data: image,
    };
  }

  @Get('file/:filename')
  serveImage(@Param('filename') filename: string, @Res() res: Response) {
    const filePath = join(process.cwd(), 'uploads', 'images', filename);
    if (!existsSync(filePath)) {
      return res.status(404).json({
        message: '文件不存在',
      });
    }
    return res.sendFile(filePath);
  }

  @Delete(':id')
  async deleteImage(@Param('id', ParseIntPipe) id: number) {
    await this.imagesService.remove(id);
    return {
      message: '图片删除成功',
    };
  }
}
